<template>
  <div class="app-container">
    <div class="designer" style="height: 100%">
      <!-- 顶部搜索和操作按钮 -->
      <div style="marginBottom: 20px">
        <el-input
          v-model="searchText"
          placeholder="请输入要查询的关键字"
          size="small"
          style="width: 200px"
        ></el-input>
        <el-button style="marginLeft: 10px" icon="el-icon-search" type="primary" size="small"  @click="searchChange">搜索</el-button>
        <el-button style="marginLeft: 10px" icon="el-icon-refresh"  size="small" @click="resetSearch">重置</el-button>
        <div style="float: right">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="operate({},'新增')">新增</el-button>
          <!-- <el-button size="small" icon="el-icon-delete" @click="multiDelPortal" :disabled="multipleSelection.length === 0">批量删除</el-button> -->
          <el-button icon="el-icon-link" size="small" @click="testConnect">测试查看</el-button>
          <el-tooltip class="item" effect="dark" content="显隐" placement="top">
            <el-button icon="el-icon-s-operation" circle @click="drawer = true" ></el-button>
          </el-tooltip>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        stripe
        style="width: 100%; marginBottom: 20px"
        size="small"
        @selection-change="handleSelectionChange"
        @row-click ="rowClick"  
        v-loading="tableLoading"
        class="tableInfo"
        :row-key="getRowKeys"
        row-key="id"
        highlight-current-row
      >
        <!-- <el-table-column
          type="selection"
          width="80"
          align="center"
          :reserve-selection="true"
        ></el-table-column> -->
        <el-table-column
          label="序号"
          width="80"
          align="center"
          v-if="!showHideData[0].hide"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{scope.$index + (page.pageNo - 1) * page.pageSize + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="code"
          label="编码"
          sortable
          align="center"
          v-if="!showHideData[1].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          sortable
          align="center"
          v-if="!showHideData[2].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="dbName"
          label="数据库"
          sortable
          align="center"
          v-if="!showHideData[3].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="creator"
          label="创建用户"
          sortable
          align="center"
          v-if="!showHideData[4].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          sortable
          align="center"
          v-if="!showHideData[5].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="description"
          label="备注"
          sortable
          align="center"
          v-if="!showHideData[6].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="operate(scope.row,'查看')">查看</el-button>
            <el-button size="small" type="text" @click="operate(scope.row,'编辑')">编辑</el-button>
            <el-button size="small" type="text" style="color: red" @click="delList(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :layout="layout"
        :total="pageTotal"
        :page-size="page.pageSize"
        :page-sizes="pageSizes"
        :current-page="page.pageNo"
        style="float: right"
        @size-change="sizeChange"
        @current-change="currentChange"
      >
      </el-pagination>
      <el-dialog
        :title="status === 'add' ? '添加数据源' : '修改数据源'"
        :visible.sync="showDialog"
        @close='cancelFields'
      >
        <el-form :model="form" ref="basicForm" label-width="120px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item
                label="名称:"
                prop="name"
                :rules="[
                  {
                    required: true,
                    message: '请填写名称',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="form.name"
                  placeholder="请填写名称"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="编码:"
                prop="code"
                :rules="[
                  {
                    required: true,
                    message: '请填写代码',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="form.code"
                  placeholder="请填写代码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item
                label="数据库:"
                prop="dbId"
                :rules="[
                  {
                    required: true,
                    message: '请选择数据库',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-cascader
                  v-model="form.dbId"
                  placeholder="请选择数据库"
                  clearable
                  :options="options"
                  :show-all-levels="false"
                  :props="{emitPath:false }"
                >
                </el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item
                label="sql语句:"
                prop="sqlSentence"
                :rules="[
                  {
                    required: true,
                    message: '请填写sql语句',
                    trigger: 'blur',
                  },
                ]"
              >
                <SqlEditor :key="fresh" v-if="showDialog" ref="sqleditor" :value="form.sqlSentence" @changeTextarea="changeTextarea($event)" />
                <div class="sqlButton"  @click="formaterSql(form.sqlSentence)">格式化</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item
                label="备注:"
                prop="description"
              >
                <el-input
                  type="textarea"
                  v-model="form.description"
                  :rows="5" 
                  maxlength="200" 
                  show-word-limit
                  placeholder="请填写备注"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelFields">取 消</el-button>
          <el-button type="primary" @click="submit()" :disabled="updateFlag">确 定</el-button >
        </div>
      </el-dialog>
      <el-dialog
        title="查看"
        :visible.sync="viewDialog"
      >
        <el-descriptions :column="2" :colon="false">
          <el-descriptions-item label="编码：">{{this.form.code}}</el-descriptions-item>
          <el-descriptions-item label="名称：" labelClassName="name">{{this.form.name}}</el-descriptions-item>
          <el-descriptions-item label="数据库：">{{this.form.dbId}}</el-descriptions-item>
          <el-descriptions-item label="创建用户：">{{this.form.creator}}</el-descriptions-item>
          <el-descriptions-item label="创建时间：">{{this.form.createTime}}</el-descriptions-item>
          <el-descriptions-item label="备注：" labelStyle='{color:red}' span="1">{{this.form.description}}</el-descriptions-item>
          <el-descriptions-item ></el-descriptions-item>
        </el-descriptions>
      </el-dialog>
      <el-dialog
        :visible.sync="testDialog"
        width="60%"
        custom-class="dialogClass"
        :fullscreen="fullScreen"
      >
        <span slot="title" class="el-dialog__title">
          测试查看
          <i class="el-icon-full-screen" v-if="!fullScreen" @click="()=>{fullScreen = true}" style="float:right;marginRight:25px;"></i>
          <i class="el-icon-aim" v-else @click="()=>{fullScreen = false}" style="float:right;marginRight:25px;"></i>
        </span>
        <el-table 
          :data="dialogData" 
          stripe 
          size="small" 
          :highlight-current-row ="highlight"
          show-overflow-tooltip
          v-loading="dialogLoading"
          :lock-scroll="true"
        >
          <el-table-column width="100px" v-for="(item,index) in fieldData" :key="index" :prop="item.name" :label="item.name"
            :min-width="item.width" show-overflow-tooltip
          >
          </el-table-column>
        </el-table>
      </el-dialog>
      <!-- 列显隐 -->
      <el-drawer :visible.sync="drawer" direction="rtl">
        <span slot="title" style="fontSize:18px;font-weight:500;color: #262626;">列显隐</span>
        <el-table
          :data="showHideData"
          size="small"
          border
          style="width: 80%; marginLeft: 10%"
        >
          <el-table-column prop="columnName" label="列名" align="center">
          </el-table-column>
          <el-table-column prop="hide" label="隐藏" align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.hide"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
  </div>
</template>
<script>
import sqlFormatter from "sql-formatter";
import SqlEditor from "./SqlEditor";
import {getIpGroupChildren,getPageDatasource,createDatasource,updateDatasource,testDatasource,getBackDatasource,deleteListDatasource} from "@/api/infra/dbDoc";
export default {
  components: {
    SqlEditor,
  },
  data() {
    return {
      updateFlag:false,
      fullScreen:false, //测试查看弹框是否全屏显示
      fresh:'',  //编辑界面渲染
      highlight:false,//是否高亮
      rowId:'',//行id
      status: "add", //判断是新增还是编辑
      form: {
        id:'',
        name: '',
        code:'',
        dbName:'',
        dbId:'',
        sqlSentence:'',
        creator:'',
        createTime:'',
        description:''
      },
      //列显隐
      showHideData: [
        {
          columnName: "序号",
          hide: false,
        },
        {
          columnName: "编码",
          hide: false,
        },
        {
          columnName: "名称",
          hide: false,
        },
        {
          columnName: "数据库",
          hide: false,
        },
        {
          columnName: "创建用户",
          hide: false,
        },
        {
          columnName: "创建时间",
          hide: false,
        },
        {
          columnName: "备注",
          hide: false,
        },
      ],
      drawer: false, //列显隐抽屉
      showDialog: false, //显示新增/编辑界面
      viewDialog:false,//显示查看界面
      tableLoading: false, //表格加载
      dialogLoading:false, //测试查看弹框加载
      testDialog:false, //数据源管理测试查看界面
      searchText: "", //关键字搜索
      layout: "prev, pager, next,sizes,jumper", //分页显示布局
      pageSizes: [10, 20, 30, 50], //分页显示每页条数选择
      pageTotal: 3, //数据总条数
      page: {
        pageNo: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      superior: [], //上级功能
      tableData:[],  //数据源管理列表数据
      dialogData:[],  //数据源管理列表数据
      fieldData:[], //测试查看表头
      multipleSelection: [], //多选
      options:[], //数据源管理界面中获取数据库id，ip
    };
  },
  mounted() {
    // 阻止默认行为
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    this.getList(); //获取列表数据
    getIpGroupChildren().then((res) => {
        if (res.code === 0) {
          res.data.map((item)=>{
            if(item.id === null){
              let child = []
              item.ipGroupChildren.map((i)=>{
                let temp = {
                  label:i.alias,
                  value:i.id,
                }
                child.push(temp)
              })
               this.options.push(
                {
                  value:item.ip,
                  label:item.ip,
                  children:child
                }
              )
            }else{
              this.options.push(
                {
                  value:item.id,
                  label:item.ip,
                }
              )
            }
          })
        }
      })
      .catch((e) => {console.log(e)});
    this.tableLoading = true
  },
  watch: {},
  methods: {
    //测试连接
    testConnect(){
      if(!this.rowId){
        this.$message.warning('请选中一条数据!')
      }else{
        this.dialogLoading = true
        testDatasource(this.rowId).then((res) => {
          if (res.code === 0) {
            this.testDialog = true
            this.fieldData = res.data.columns
            this.dialogData = res.data.rowMaps
            this.dialogLoading = false
          }
        })
        .catch((e) => {
          this.dialogLoading = false
        });
      }
    },
    //sql操作
    changeTextarea(val) {
      this.$set(this.form, "sqlSentence", val);
    },
    //格式化
    formaterSql(val) {
      let dom = this.$refs.sqleditor;
      dom.editor.setValue(sqlFormatter.format(dom.editor.getValue()));
    },
    //多选rowkey
    getRowKeys(row) {
      return row.id;
    },
    //获取列表数据
    getList() {
      this.tableLoading = false;
      let params = {
        ...this.page, //页配置
        keyword: this.searchText, //名称关键字
      };
      getPageDatasource(params).then((res) => {
        if (res.code === 0) {
          res.data.list.forEach((item)=>{
            item.createTime = this.getDateTime(item.createTime)
          })
          this.tableData = res.data.list;
          this.pageTotal = res.data.total;
          this.tableLoading = false;
        }
      })
      .catch((e) => {
        this.tableLoading = false;
      });
    },
    //多选，数据选择改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //行点击事件
    rowClick(row,column,event){
      this.highlight = true
      this.rowId = row.id
    },
    //时间戳转日期时间
    getDateTime(time) {
      if (!time) return ''
      let date = new Date(time)
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      let hour = date.getHours()
      let minute = date.getMinutes()
      let second = date.getSeconds()
      return `${year}-${month<10?'0':''}${month}-${day<10?'0':''}${day} ${hour<10?'0':''}${hour}:${minute<10?'0':''}${minute}:${second<10?'0':''}${second}`
    },
    //编辑/查看回显
    getBackAll(id){
      Object.keys(this.form).forEach(key =>{this.form[key] = ''})
      getBackDatasource(id).then((res) => {
        if (res.code === 0) {
          this.form.id= res.data.id;
          this.form.name =res.data.name;
          this.form.code =res.data.code;
          this.form.dbName =res.data.dbName;
          this.form.dbId = res.data.dbId;
          this.form.sqlSentence = res.data.sqlSentence;
          this.form.creator = res.data.creator;
          this.form.createTime = this.getDateTime(res.data.createTime);
          this.form.description = res.data.description;
          this.fresh = Date.now()
        }
      })
      .catch((e) => {
        this.tableLoading = false;
      });
    },
    operate(row,status){
      if(status==='新增'){
        this.status = 'add'
        Object.keys(this.form).forEach(key =>{this.form[key] = ''})
        this.showDialog = true;
      }else if(status === '编辑'){
        this.status = 'edit'
        this.getBackAll(row.id)
        this.showDialog = true;
      }else{
        this.status = 'view'
        this.getBackAll(row.id)
        this.viewDialog = true
      }
    },
    //删除
    delList(row) {
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          deleteListDatasource(row.id).then((res) => {
            if (res.code === 0) {
              this.$message.success("删除成功");
              this.getList();
            }
          })
          .catch((e) => {
            this.tableLoading = false;
          });
      })
      .catch((e) => console.log(e));
    },
    //批量删除
    // multiDelPortal() {
    //   this.$confirm("是否确认删除", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   }).then(() => {
    //     let ids = this.multipleSelection.map((item) => {
    //       return item.id;
    //     });
    //     batchDelPortal(ids).then(res => {
    //       if (res.code === 0) {
    //         this.$message.success('删除成功')
    //         setTimeout(() => {
    //           window.location.reload()
    //         }, 1000)
    //       } else {
    //         this.$message.error('所选数据删除失败！')
    //       }
    //     }).catch(e => console.log('批量删除：', e))
    //   });
    // },
    //搜索
    searchChange() {
      this.page.pageNo = 1;
      this.tableLoading = true;
      this.getList();
    },
    //搜索重置
    resetSearch() {
      this.searchText = "";
      this.searchChange();
    },
    //每页条数更改
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.page.pageNo = 1;
      this.tableLoading = true;
      this.getList();
    },
    //页码更改
    currentChange(current) {
      this.page.pageNo = current;
      this.tableLoading = true;
      this.getList();
    },
    cancelFields () {
      this.showDialog = false
      this.$refs["basicForm"].clearValidate()
    },
    //确定提交
    submit(){
      this.updateFlag = true
      this.$refs["basicForm"].validate((valid) => {
        if (!valid) {
          this.updateFlag = false
          return;
        }
        if(this.status === 'add'){
          let params = {
            name: this.form.name,
            code: this.form.code,
            dbId:this.form.dbId,
            sqlSentence: this.form.sqlSentence,
            description:this.form.description
          }
          //数据源创建
          createDatasource(params).then((res) => {
            if (res.code === 0) {
              this.$message.success('新增成功')
              this.showDialog = false
              this.getList()
            }
          })
          .finally(() => {
            setTimeout(() => {
              this.updateFlag = false;
            }, 1000)
          });
        }else{
          let params = {
            id:this.form.id,
            name: this.form.name,
            code: this.form.code,
            dbId:this.form.dbId,
            sqlSentence: this.form.sqlSentence,
            description:this.form.description
          }
          //数据库创建
          updateDatasource(params).then((res) => {
            if (res.code === 0) {
              this.$message.success('修改成功')
              this.showDialog = false
              this.getList();
            }
          })
          .finally(() => {
            setTimeout(() => {
              this.updateFlag = false;
            }, 1000)
          });
        }
      });
    }
  },
};
</script>
<style lang="scss" scoped>
  .sqlButton {
    position: absolute;
    right: 10px;
    bottom: 4px;
    cursor: pointer;
    text-decoration: underline;
    z-index: 2;
  }
  .designer {
    .base {
      margin-right: 20%;
      margin-left: 15%;
      margin-top: 5%;

      .el-form-item {
        margin-bottom: 40px;
      }
    }

    .el-input--mini {
      width: 80px;
    }

    .designHeader {
      display: flex;
      justify-content: space-around;
      align-items: center;

      .designStep {
        display: flex;
        justify-content: center;
        width: 100%;
        margin-left: 10%;

        .designStepItem {
          width: 33.3%;
          display: flex;
          align-items: center;
          justify-content: space-around;

          .designStepLine {
            display: inline-block;
            width: calc(100% - 110px);
            height: 2px;
          }

          .designStepIndex {
            font-size: 16px;
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            text-align: center;
            line-height: 30px;
            margin-right: 5px;
            margin-left: 5px;
            font-weight: bold;
          }

          .designStepTitle {
            font-size: 14px;
            font-weight: bold;
            width: 70px;
          }
        }
      }
    }
  }

</style>
<style lang="scss">
  .el-descriptions-item__label:not(.is-bordered-label){
    width: 20%;
    text-align: right;
    align-items: center;
    margin: auto 2%;
  }
  .el-descriptions-item__content{
    width: 75%;
  }
  .el-dialog__header{
    border-bottom: 1px solid #eee;
  }
  .el-dialog__title {
    font-size: 15px;
    color: #303133;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .el-dialog__body{
    padding-top: 20px;
  }
  .designer {
    .el-table {
      box-sizing: border-box;

      &::before {
        height: 0px;
      }
    }

    .el-table--border::after,
    .el-table--group::after {
      width: 0px;
      height: 0px;
    }

    .tableInfo {
      .el-table__cell {
        // border-bottom: 0px;
        padding: 3px;
      }
    }
  }
</style>
